package com.netty.chat.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netty.chat.entity.User;
import com.netty.chat.message.MessageResponse;
import com.netty.chat.server.ChatHandler;
import com.netty.chat.service.ChatService;
import com.netty.chat.service.UserService;
import com.netty.chat.vo.ChatItem;
import com.netty.chat.vo.UserInfo;
import com.netty.chat.vo.UserSocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

import static com.netty.chat.constant.ChatConstant.GLOBLE_CHAT_ID;
import static com.netty.chat.constant.ChatConstant.GLOBLE_CHAT_RECORD;

@Controller
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Autowired
    private ChatService chatService;
    @Autowired
    ObjectMapper objectMapper;


    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, RedirectAttributesModelMap model, HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            return "redirect:/toChat";
        }
        user = userService.query(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (user != null && user.getPassword().equals(password)) {
            httpSession.setAttribute("user", user);
            //TODO 获取聊天对象
            return "redirect:/toChat";
        }
        //登录失败
        model.addFlashAttribute("error", "用户名或密码错误！");
        return "redirect:/toLogin";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession httpSession) throws JsonProcessingException {
        User user = (User) httpSession.getAttribute("user");
        httpSession.removeAttribute("user");
        if (user != null) {
            UserSocketChannel channel = ChatHandler.userChannel.get(user.getId());
            if (channel != null) {
                channel.getChannel().close();
            }
            ChatHandler.userChannel.remove(user.getId());
            //广播下线消息
            MessageResponse messageResponse = new MessageResponse();
            messageResponse.setMessageType(0);
            messageResponse.setChannelId(GLOBLE_CHAT_ID);
            messageResponse.setInfo(user.getUsername()+"下线了！");
            ChatHandler.globleChannelGroup.writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(messageResponse)));
            ChatHandler.chatRecord.get(GLOBLE_CHAT_RECORD).add(messageResponse);
        }
        return "login";
    }

    @RequestMapping("/toChat")
    public String toChat(HttpSession httpSession, Model model) {
        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            List<ChatItem> chatItemList = chatService.getChatItems(user.getId());
            model.addAttribute("chatItemList", chatItemList);
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(user, userInfo);
            model.addAttribute("userInfo", userInfo);
        } else {
            return "redirect:/toLogin";
        }
        return "index";
    }
}